package cn.yll.order.business;

import cn.yll.api.order.request.OrderLineRequest;
import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.exception.BsException;
import cn.yll.order.entity.GoodsEntity;
import cn.yll.order.service.IGoodsService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 商品服务
 * @author yangll
 */
@Service
public class GoodBusiness {

    @Autowired
    private IGoodsService goodsService;

    @Transactional(rollbackFor = Exception.class)
    public void checkPriceAndReduceNum(List<OrderLineRequest> lines) {
        //验证商品ID参数，查询商品单价
        for (OrderLineRequest line : lines) {
            if (Objects.isNull(line.getGoodId()) || line.getPrice() <= 0 || line.getBuyNum() <= 0) {
                throw new BsException(BsErrEnum.PARAM_ILLEGAL, "商品ID、购买数量或单价错误");
            }
            UpdateWrapper<GoodsEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.setSql("good_num = good_num - " + line.getBuyNum());
            updateWrapper.eq("id", line.getGoodId());
            updateWrapper.eq("price", line.getPrice());
            updateWrapper.gt("good_num", line.getBuyNum());
            boolean result = goodsService.update(updateWrapper);
            if (!result) {
                throw new BsException(BsErrEnum.REQUEST_ERROR, "商品数量不足，请重新下单");
            }
        }
    }
}
